package com.example.lot_lock;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class add_change_equip extends AppCompatActivity {


    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    //Toast.makeText(add_change_equip.this, "设备添加成功", Toast.LENGTH_SHORT);
                    insertSuccess();
                    break;
                case 2:
                    //Toast.makeText(add_change_equip.this, "设备删除完成", Toast.LENGTH_SHORT);
                    deleteSuccess();
                    break;
                case 3:
                    //Toast.makeText(add_change_equip.this, "删除设备失败-此账户下无此设备", Toast.LENGTH_SHORT);
                    deleteError();
                    break;
            }
        }
    };
    private void insertSuccess(){//添加设备成功对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(add_change_equip.this);
        builder.setTitle("添加成功").setIcon(R.mipmap.one_image).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    updateEquip();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        AlertDialog ad = builder.create();
        ad.show();
    }
    private void deleteSuccess(){//删除设备成功对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(add_change_equip.this);
        builder.setTitle("删除成功").setIcon(R.mipmap.one_image).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    updateEquip();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        AlertDialog ad = builder.create();
        ad.show();
    }
    private void deleteError(){//删除设备失败对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(add_change_equip.this);
        builder.setTitle("此账户下无此设备").setIcon(R.mipmap.one_image).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        AlertDialog ad = builder.create();
        ad.show();
    }
    private ImageButton button_back = null;
    private ImageButton button_delete = null;
    private ImageButton imageButton[] = {null, null, null};
    static public ApplicationTCP applicationTCP = null;
    static public InputStream inputStream = null;
    static public OutputStream outputStream = null;
    static public String []equipRecond = new String[10];//十条最近互动记录
    //---------储存设备信息-------

    boolean []state = new boolean[3];//设备在线状态
    String []equipId =  new String[3];//设备ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_change_equip);

        applicationTCP = (ApplicationTCP)add_change_equip.this.getApplication();
        inputStream = applicationTCP.getIn();
        outputStream = applicationTCP.getOut();
        button_back = findViewById(R.id.back);
        button_delete = findViewById(R.id.delete);
        imageButton[0] = findViewById(R.id.ImageButton_add_1);
        imageButton[1] = findViewById(R.id.ImageButton_add_2);
        imageButton[2] = findViewById(R.id.ImageButton_add_3);
        try {
            updateEquip();//更新设备状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //删除设备按钮
        button_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete_equip_dialog();
            }
        });
        //返回按钮
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                onBackPressed();
            }
        });
       Listen_Imagebutton();
    }
    //在线更新设备、获得设备ID和在线状态
    private void updateEquip() throws InterruptedException {
        applicationTCP.updateEquipState();
        state[0]=applicationTCP.equipState1();
        state[1]=applicationTCP.equipState2();
        state[2]=applicationTCP.equipState3();
        equipId[0]=applicationTCP.getId1();
        equipId[1]=applicationTCP.getId2();
        equipId[2]=applicationTCP.getId3();
        SetequipState();
    };
    //显示状态
    //count:用户控制的设备数量
    //state:设备的状态
    private void SetequipState() {//更新UI门锁状态、count设备个数、state设备状态
        if (equipId[0].equals("a000")) {
            imageButton[0].setBackgroundResource(R.mipmap.add);
        }else{
            imageButton[0].setBackgroundResource(state[0]==true ?  R.mipmap.one_online : R.mipmap.one_unonline);
        }
        if (equipId[1].equals("a000")) {
            imageButton[1].setBackgroundResource(R.mipmap.add);
        }else{
            imageButton[1].setBackgroundResource(state[1]==true ?  R.mipmap.two_online : R.mipmap.two_unonlie);
        }
        if (equipId[2].equals("a000")) {
            imageButton[2].setBackgroundResource(R.mipmap.add);
        }else{
            imageButton[2].setBackgroundResource(state[2]==true ?  R.mipmap.three_online : R.mipmap.three_unonline);
        }
    }
//---------------------跳转到控制页面--------
    private void user_control(){
        Intent intent = new Intent(add_change_equip.this, user_control.class);
        startActivity(intent);
    }
    //----------------------------------------------
    //----------------三个设备按钮---------------------
    //----------------------------------------------

    private void Listen_Imagebutton() {
        imageButton[0].setOnClickListener(new View.OnClickListener() {//第一个设备
            @Override
            public void onClick(View v) {
                if(equipId[0].equals("a000")){
                    //Toast.makeText(add_change_equip.this, "No equip", Toast.LENGTH_SHORT).show();
                    add_equip_dialog();
                }else{
                    jumpUserUi(equipId[0]);
                }
            }
        });

        imageButton[1].setOnClickListener(new View.OnClickListener() {//第二个设备
            @Override
            public void onClick(View v) {
                if(equipId[1].equals("a000")){
                    //Toast.makeText(add_change_equip.this, "No equip", Toast.LENGTH_SHORT).show();
                    add_equip_dialog();
                }else{
                    jumpUserUi(equipId[1]);
                }
            }
        });
        imageButton[2].setOnClickListener(new View.OnClickListener() {//第三个设备
            @Override
            public void onClick(View v) {
                if(equipId[2].equals("a000")){
                    //Toast.makeText(add_change_equip.this, "No equip", Toast.LENGTH_SHORT).show();
                    add_equip_dialog();
                }else{

                        jumpUserUi(equipId[2]);

                }
            }
        });
    }
//==================弹出添加设备的对话框
    private void add_equip_dialog(){//添加设备
        View view = LayoutInflater.from(this).inflate(R.layout.adddialog,null, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        AlertDialog ad = builder.create();

        Button adddialog_btn_1 = view.findViewById(R.id.adddialog_button_1);
        EditText adddialog_edit_1 = view.findViewById(R.id.adddialog_equip_ID);
        adddialog_btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//确定按钮
                String equipId = adddialog_edit_1.getText().toString();
                if(equipId.length() ==4 && equipId.charAt(0)=='a') {
                    String SendData = '5' + applicationTCP.userNmae + '+' + adddialog_edit_1.getText().toString() + '\n';
                    byte[] Byte = new byte[3];
                    new Thread(new Runnable() {//发送添加指令
                        @Override
                        public void run() {
                            try {
                                outputStream.write(SendData.getBytes());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        inputStream.read(Byte, 0, 1);
                                        if ((char) Byte[0] == '1') {
                                            Message message = new Message();
                                            message.what = 1;
                                            handler.sendMessage(message);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        }

                    }).start();
                }else{
                    Toast.makeText(add_change_equip.this, "设备ID格式有误", Toast.LENGTH_SHORT).show();
                }
                ad.dismiss();//对话框消失
            }
        });
        ad.show();
    }
 //-------------------------删除设备----------------------
    private void delete_equip_dialog(){//删除设备

        View view = LayoutInflater.from(this).inflate(R.layout.deletedialog,null, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        AlertDialog ad = builder.create();

        Button delete_button_1 = view.findViewById(R.id.deletedialog_button_1);
        Button delete_button_2 = view.findViewById(R.id.deletedialog_button_2);
        EditText editText = view.findViewById(R.id.deletedialog_equip_ID);


        delete_button_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String equipId = editText.getText().toString();
                if (equipId.length() == 4 && equipId.charAt(0) == 'a') {
                    String SendData = '6' + applicationTCP.userNmae + '+' + editText.getText().toString() + '\n';
                    byte[] Byte = new byte[3];
                    new Thread(new Runnable() {//发送添加指令
                        @Override
                        public void run() {
                            try {
                                outputStream.write(SendData.getBytes());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        inputStream.read(Byte, 0, 1);
                                        if ((char) Byte[0] == '1') {
                                            Message message = new Message();
                                            message.what = 2;
                                            handler.sendMessage(message);
                                        } else {
                                            Message message = new Message();
                                            message.what = 3;
                                            handler.sendMessage(message);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }).start();
                        }
                    }).start();

                    ad.dismiss();//对话框消失
                }
                else{
                    Toast.makeText(add_change_equip.this, "设备ID格式错误",Toast.LENGTH_SHORT).show();
                }
            }
        });
        ad.show();
    }
//------------------------跳转的用户控制页面----------------
    /*
    * 得到设备ID
    * 访问设备数据库
    * 得到近10条访问数据
    * 跳转下个页面
    * */
public void jumpUserUi(String equipId){

        //userRecord userrecord = new userRecord();
        //userrecord.start();
        //userrecord.join();
    Intent intent = new Intent(add_change_equip.this, user_control.class);
    intent.putExtra("equipID", equipId);
    startActivity(intent);
    }
}
class userRecord extends Thread{
    @Override
    public void run() {
        super.run();

        String SendData = "7" + add_change_equip.applicationTCP.getId1() + '\n';
        byte[] Byte = new byte[50];
        try {//发送数据
            add_change_equip.outputStream.write(SendData.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {//接受数据
            add_change_equip.inputStream.read(Byte,0,50);
            add_change_equip.equipRecond[0] = ""+ new String(Byte, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
